<?php

namespace App\Models;

use App\Models\Business\Collection as CollectionModel;
use App\Models\Config as ConfigModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use HasFactory;

    protected $table = 'category';

    // 自动写入时间戳
    public $timestamps = true;

    // 时间类型
    protected $dateFormat = 'U';

    // 自定义创建时间字段
    const CREATED_AT = 'createtime';

    // 自定义更新时间字段
    const UPDATED_AT = 'updatetime';

    protected $guarded = [];

    protected $appends = [
        'type_text',
        'flag_text',
        'image_cdn',
        'createtime_text',
        'collection_status'
    ];

    public function getFlagList()
    {
        return ['hot' => '热门', 'index' => '首页', 'recommend' => '推荐'];
    }

    public function getFlagTextAttribute()
    {
        $valueArr = explode(',', $this->flag);
        $list = $this->getFlagList();
        return implode(',', array_intersect_key($list, array_flip($valueArr)));
    }

    public function getTypeTextAttribute()
    {
        $TypeJson = ConfigModel::where(['name' => 'categorytype'])->value('value');

        $TypeList = json_decode($TypeJson,true);

        return $TypeList[$this->type] ?? '';
    }

    public function getImageCdnAttribute()
    {
        $url = ConfigModel::where(['name' => 'url'])->value('value');

        $url = env('SITE_URL',$url);

        $image = httpRequest($url . '/base/category/image',['cateid' => $this->id]);

        return $image;
    }

    public function getCreatetimeTextAttribute()
    {
        return date('Y-m-d H:i:s',$this->attributes['createtime']);
    }

    public function getCollectionStatusAttribute()
    {
        $busid = request('busid',0);

        $collection = CollectionModel::where([
            ['busid','=', $busid],
            ['cateid','=',$this->id],
        ])->first();

        if($collection)
        {
            return true;
        }else{
            return false;
        }
    }
}
